<?php
// +----------------------------------------------------------------------
// | 商家模块
// +----------------------------------------------------------------------

namespace app\mall\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\mall\model\Goods as GoodsModel;
use app\mall\model\Order as OrderModel;
use app\mall\model\Qrcode as QrcodeModel;
use app\mall\model\Merch as MerchModel;
use app\mall\model\Child as ChildModel;
use app\user\model\Level as LevelModel;
use app\user\model\Member as MemberModel;
use app\user\model\Vip as VipModel;
use qrcode\Qrcode as QrcodeTool;
use util\Tree;
use util\File;
use util\PHPZip;
/**
 * 二维码控制器
 * @package app\mall\admin
 */
class Qrcode extends Admin
{
    /**
     * 二维码列表
     */
    public function index()
    {
//		$this->success('功能研发中…');
        // 查询
        $map = $this->getMap();
		$order = $this->getOrder('sort,id desc');
		
        // 数据列表
        $data_list = QrcodeModel::where($map)->order($order)->paginate(config('paginate'));
		foreach ($data_list as $key => $value){
			$data_list[$key]['qrcode'] = '<i class="fa fa-fw fa-qrcode"></i>';
		}
		// 批量新增
		$btnAdd = [
			'title' => '批量新增',
			'icon'  => 'fa fa-plus-circle',
			'class' => 'btn btn-primary',
			'href'  => url('addall')
		];
		// 导出按钮
		$btnExport = [
			'title' => '打包二维码',
			'icon'  => 'fa fa-fw fa-save',
			'class' => 'btn btn-default js-get',
			'href'  => url('export')
		];

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setSearch(['id' => '二维码ID']) // 设置搜索框
            ->addColumns([ // 批量添加数据列
               ['id', 'ID'],
			   ['qrcode', '回溯码', 'link', url('qrcode/qrcode', ['id'=>'__id__']), '_blank', 'pop', '回溯码'],
                ['suid', '回溯码编号', 'text'],
               ['view', '扫码次数', 'text'],
               ['status', '状态', 'switch'],
               ['right_button', '操作', 'btn']
            ])
            ->addTopButtons('add,enable,disable') // 批量添加顶部按钮
			->addTopButton('custom', $btnAdd) // 添加批量新增
			->addTopButton('custom', $btnExport) // 添加导出按钮
            ->addRightButton('edit') // 添加右侧按钮
            ->addRightButton('delete', ['data-tips' => '删除二维码无法恢复！']) // 添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }

    /**
     * 新增二维码
     */
    public function add()
    {
        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Qrcode');
            if(true !== $result) $this->error($result);
            $data['suid'] = $this->getrandstr(8);
            $data['codeurl'] = 'https://'.$_SERVER['HTTP_HOST'].'/mall/index/sao_qrcode?suid='.$data['suid'];
//            var_dump($data);exit;
            $qrcode = new QrcodeTool;
            $fileauth = './uploads/sao_qrcode/';
            $data['url'] = '/uploads/sao_qrcode/'.$data['suid'].'.png';
            $qrcode->save($data['codeurl'], 0,0,$fileauth,$data['suid']);
            if ($qrcode = QrcodeModel::create($data)) {
                // 记录行为
                action_log('qrcode_add', 'merch_qrcode', $qrcode->id, UID, '二维码ID'.$qrcode->id);
				// 同步终端信息
                $this->success('新增成功', 'index');
            } else {
                $this->error('新增失败');
            }
        }

        // 显示添加页面
        return ZBuilder::make('form')
            ->addFormItems([
				['radio', 'status', '立即启用', '', ['否', '是'], 1],
                ['text:8', 'sort', '排序', '', 100],
            ])
            ->fetch();
    }

    /**
     * 编辑二维码
     */
    public function edit($id = '')
    {
        if ($id === 0) $this->error('参数错误');
		// 获取数据
		$info = QrcodeModel::where('id', $id)->find();
		
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'Qrcode');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            if (QrcodeModel::update($data)) {
                // 记录行为
                action_log('qrcode_edit', 'merch_qrcode', $id, UID, '二维码ID'.$id);
				cache('merch_qrcode_info_'. $id, null);
                return $this->success('编辑成功', 'index');
            } else {
                return $this->error('编辑失败');
            }
        }
		

        // 显示编辑页面
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden', 'id'],
                ['radio', 'status', '立即启用', '', ['否', '是']],
                ['text:8', 'sort', '排序'],
            ])
            ->setFormData($info)
            ->fetch();
    }
    // 二维码图片
	public function qrcode($id = 0)
	{
        $codes = QrcodeModel::find($id)->toArray();
		//生成路径
		$img = real_url('api/qrcode/getimg', ['id' => $id]);

		$table_data = [
		    ['<img src="'.$codes['url'].'" style="margin:20px auto; display:block; width:240px">'],
		    ['<span style="text-align:center; width:100%; display:block;">二维码编码：'.$codes['suid'].'</span>'],
		];
		
		return ZBuilder::make('form')
		    ->setPageTitle('查看二维码') // 设置页面标题
		    ->addFormItems([ // 批量添加表单项
		        ['complexTable', 'qrcode', '二维码', $table_data]
		    ])
			->hideBtn(['submit', 'back'])
		    ->fetch();
	}
    /**
     * 打包二维码
     * @return mixed
     */
    public function export()
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        if (!is_array($ids)) $ids = explode(',', $ids);

        if (!$ids) $this->error('请选择二维码');

        // 模块导出目录
        $qrcode_dir = root_path() . 'export/qrcode';

        // 删除旧的导出数据
        if (is_dir($qrcode_dir)) {
            File::del_dir($qrcode_dir);
        }
        mkdir($qrcode_dir, 0777, true);

        foreach ($ids as $id) {
            $info = QrcodeModel::find($id);
            $file = public_path() . 'uploads/sao_qrcode/' . $info['suid'] . '.png';

            if (!is_file($file)) {
                $this->success('打包失败1！');
            } else {
                $info = QrcodeModel::find($id);
                if (!$info) continue;
                //生成路径
                $qrcode = new QrcodeTool;
                $qrcode->save($info['codeurl'], 14, 0, 'uploads/sao_qrcode/', $info['suid']);
                copy($file, $qrcode_dir . '/' . $info['suid'] . '.png');
            }

        }

        // 打包下载
        $archive = new PHPZip;
        $url = $archive->ZipAndDownload($qrcode_dir, '二维码');
        $this->success('打包成功', $url);

    }
	/**
	 * 打包二维码
	 * @return mixed
	 */
	public function exportsed()
	{
        if(request()->isPost()){
            $data = request()->post();
            // 查询条件
            $map =[];
            $map[] =['status', '=', 1];
            // 排序条件
            $order = 'create_time desc';

            // 获取查询数据，数组形式
            $code_list =  QrcodeModel::where($map)->order($order)->select()->toArray();

            foreach ($code_list as $key => $value){
                // 实例化
                $order_list[$key]['suid'] = $value['suid'];
                $order_list[$key]['view'] = $value['view'];
                $order_list[$key]['create_time'] = format_time($value['create_time']);
//                $order_list[$key]['warename'] = $value['warename'];
//                $order_list[$key]['proname'] = $value['proname'];
//                $order_list[$key]['wareuser'] = $value['wareuser'];

//                $order_list[$key]['realname'] = $value['realname'];
//                $order_list[$key]['sutime'] = format_time($value['sutime']);
//                $order_list[$key]['dainame'] = $value['dainame'];
//                $order_list[$key]['daijibie'] = $value['daijibie'];
//                $order_list[$key]['daiaddress'] = $value['daiaddress'];
//                $order_list[$key]['daimobile'] = $value['daimobile'];
                $order_list[$key]['codeurl'] = $value['codeurl'];
            }
            $return['list'] = $order_list;
            // 设置表头信息（对应字段名,显示表头名称）
            $head[0] = [
                'suid' 	=> '二维码编号',
                'view' 	=> '查看次数',
                'create_time' 	=> '创建时间',
//                'warename' 	=> '仓库名称',
//                'proname' 	=> '产品名称',
//                'wareuser' 	=> '仓管员',
//                'realname' 	=> '微信昵称',
//                'sutime' 	=> '出库时间',
//                'dainame' => '代理人姓名',
//                'daijibie' => '代理人级别',
//                'daiaddress'  	=> '代理人地址',
//                'daimobile'  	=> '代理人联系方式',
                'codeurl'  	=> '二维码链接',
            ];
            // 向第一行插入表头
            $return['list'] = array_merge($head, $return['list']);

            // 表格筛选字段
            $return['field'] = [];
            foreach ($head[0] as $key => $value){
                $return['field'][] = $key;
            }

            $return['title'] = '溯源码'.$data['date1'].'_'.$data['date2'];
            // 返回数据（[导出文件名:title、字段信息:field、具体数据:list]）
            $this->success('导出成功', '', $return);
        }
        $js = <<<EOF
			<script type="text/javascript">
			$('input#date1').attr("autocomplete","off");
			$('input#date2').attr("autocomplete","off");
			</script>
EOF;

        return ZBuilder::make('form')
            ->setPageTips('请按需求选择数据筛选', 'info')
            ->setPageTitle('选择数据')
            ->addDaterange('date1,date2', '日期范围', '<span class="text-danger">最长跨度45天</span>')
            ->layout(['ids' => 8, 'date1' => 8, 'date2' => 8])
            ->hideBtn(['submit', 'back'])
            ->addBtn('<button type="button" id="get_data" class="btn btn-info">导出数据</button>')
            ->js('js/excel,js/export') // 引入外部excel.js文件
            ->setExtraJs($js)
            ->fetch();
	}
	/**
	 * 批量新增二维码
	 */
	public function addall()
	{
	    // 保存数据
	    if ($this->request->isPost()) {

	        // 表单数据
	        $data = $this->request->post();

			if ($data['numbers'] <= 0 || $data['numbers'] > 100){
				$this->error('数量必须介于1-100之间');
			}
			$data_list = [];
            $qrcode = new QrcodeTool;
			for ($i = 0; $i < $data['numbers']; $i++){
			    $suid = $this->getrandstr(8);
				$data_list[$i] = [
				    'suid' => $suid,
                    'codeurl' => 'https://'.$_SERVER['HTTP_HOST'].'/mall/index/sao_qrcode?suid='.$suid
                ];

                $fileauth = './uploads/sao_qrcode/';
                $qrcode->save($data['codeurl'], 0,0,$fileauth,$suid);
			}
			$qrcode = new QrcodeModel;
	        if ($qrcode->saveAll($data_list)) {
	            $this->success('新增成功', 'index');
	        } else {
	            $this->error('新增失败');
	        }
	    }
	    // 显示添加页面
	    return ZBuilder::make('form')
	        ->addFormItems([
	            ['text:8', 'numbers', '新增数量', '', 10],
	        ])
	        ->fetch();
	}

    /**
     * 生成随机字符串
     * @param null $length 长度
     */
    function getrandstr($length){
        //字符组合
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len = strlen($str)-1;
        $randstr = '';
        for ($i=0;$i<$length;$i++) {
            $num=mt_rand(0,$len);
            $randstr .= $str[$num];
        }
        return $randstr;
	}

    /**
     * 删除二维码
     * @param null $ids 二维码id
     */
    public function delete($record = [])
    {
		return $this->setStatus('delete');
    }

    /**
     * 启用二维码
     * @param array $record 行为日志
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用二维码
     * @param array $record 行为日志
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置二维码状态：删除、禁用、启用
     * @param string $type 二维码：enable/disable
     * @return mixed
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids/a');
		// 清除缓存
		foreach ($ids as $id){
			cache('merch_qrcode_info_'. $id, null);
		}
        $column_delete = is_array($ids) ? '' : $ids;
        $column_names  = QrcodeModel::where('id', 'in', $ids)->column('id');

        return parent::setStatus($type, ['qrcode_'.$type, 'mall_qrcode', $column_delete, UID, implode('、', $column_names)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id      = input('post.pk', '');
        $field   = input('post.name', '');
        $value   = input('post.value', '');
		cache('merch_qrcode_info_'. $id, null);
        $column  = QrcodeModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $column . ')，新值：(' . $value . ')';
        return parent::quickEdit(['qrcode_edit', 'merch_qrcode', $id, UID, $details]);
    }
}